package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


@Component
public class RedisIdWorker {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //TODO:1.初始化开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    //序列号位数
    private static final int COUNT_BITS = 32;
    private static final long MAX_COUNT = ~(-1L << COUNT_BITS);

    public Long nextId(String key) {
        //2.TODO:获取当前时间戳
        long epochSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        //当前时间戳-初始时间戳
        long l = epochSecond - BEGIN_TIMESTAMP;
        if(l>MAX_COUNT){
            throw new RuntimeException("时间戳超出最大值");
        }
        //TODO:3.获取序列号
        //获取当前时间（精确到天）
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMdd"));
        Long increment = stringRedisTemplate.opsForValue().increment("icr" + key + ":" + format);
        //TODO:拼接字符春
        return l << COUNT_BITS | increment;
    }
}
